﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LightCAD.Runtime;

namespace LightCAD.UI
{
    public static class UIUtils
    {
        /// <summary>
        /// 触发命令
        /// </summary>
        /// <param name="uiCmdName">UI发出的命令名, 如"tbi_Line"</param>
        /// <exception cref="Exception"></exception>
        public static void ExecuteCommand(string uiCmdName)
        {
            string cmdString = uiCmdName.Replace("_", " ");
            const int delay = 10;
            AsyncUtils.Execute(
                () =>
                    {
                        App.Current.ActiveWindow.Invoke(() => { CommandCenter.ActiveInstance.Execute(cmdString.ToUpper()); }); // 在UI线程上执行
                    },
                delay);
        }

        internal static MainUIWindow? GetMainUI(Control control)
        {
            var owner = GetParent<Form>(control).Owner;
            if (owner == null) return null;
            var mainWin = owner as MainUIWindow;
            if (mainWin == null) return null;
            return mainWin;
        }

        internal static T GetParent<T>(Control control) where T : Control
        {
            while (control != null)
            {
                if (control.Parent is T)
                    return (T)control.Parent;
                control = control.Parent;
            }
            return default(T);
        }

        public static string SubString(Graphics g, Font font, string text, int maxWidth)
        {
            // 测量字符串的宽度
            float width = g.MeasureString(text, font).Width;

            // 如果字符串的宽度超过最大宽度，则进行裁剪
            if (width > maxWidth)
            {
                // 裁剪字符串
                while (width > maxWidth && text.Length > 0)
                {
                    text = text.Substring(0, text.Length - 1);
                    width = g.MeasureString(text + "...", font).Width;
                }
                // 在裁剪后的字符串后添加省略号
                text += "...";
            }
            return text;
        }

        public static TimerTask SetTimeout(Control ctrl, Action action, int interval)
        {
            return TimerUtil.SetTimeout(() => {
                ctrl.Invoke(action);
            }, interval);
        }
    }

}